<?php

namespace App\Http\Controllers\User;

use App\Models\UserGroup;
use App\Models\UserRelation;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class EmployeeController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->assign(['menu'=>'employee']);
    }

    public function index()
    {
        $this->assign([
            'username'=>'',
            'time_begin'=>'',
            'time_end'=>'',
            'gid'=>'',
            'groups'=>UserGroup::userGroups()->orderBy('creditslower')->get()
        ]);

        $queryParams = [];
        $uid = $this->request->get('uid', 0);
        if (!$uid) $uid = $this->uid;
        $query = UserRelation::with(['user.group', 'wallet'])->where('upuid', $uid);

        $username = $this->request->get('username', '');
        if ($username)
        {
            $queryParams['username'] = $username;
            $query = $query->whereHas('user', function ($query) use ($username){
                return $query->where('username', 'LIKE', "%$username%");
            });
        }

        $time_begin = $this->request->get('time_begin', '');
        if ($time_begin)
        {
            $queryParams['time_begin'] = $time_begin;
            $query = $query->where('created_at', '>', strtotime($time_begin));
        }

        $time_end = $this->request->get('time_end', '');
        if ($time_end)
        {
            $queryParams['time_end'] = $time_end;
            $query = $query->where('created_at', '<', strtotime($time_end));
        }

        $gid = $this->request->get('gid', 0);
        if ($gid)
        {
            $queryParams['gid'] = $gid;
            $query = $query->whereHas('user', function ($query) use ($gid){
                return $query->where('gid', $gid);
            });
        }

        $this->assign($queryParams);

        $items = $query->orderByDesc('created_at')->paginate(20);

        return $this->view('user.employee', [
            'items'=>$items,
            'pagination'=>$items->appends($queryParams)->render()
        ]);
    }

    public function export()
    {
        $data = [
            [
                '用户名',
                '个人业绩',
                '个人佣金',
                '会员等级',
                '绑定时间'
            ]
        ];
        UserRelation::with(['user.group', 'wallet'])->where('upuid', $this->uid)
        ->orderByDesc('created_at')->get()->map(function (UserRelation $relation) use (&$data){
            $data[] = [
                $relation->user->username,
                $relation->wallet->total_cost,
                $relation->Wallet->commission,
                $relation->user->group->title,
                @date('Y-m-d H:i:s', $relation->created_at)
            ];
        });


        return collect($data)->downloadExcel(
            'relations.xls',
            'Xls',
            false
        );
    }
}
